import * as express from "express";
import * as bodyParser from "body-parser";
import { Request, Response } from "express";
import { AppDataSource } from "./data-source";
import Routes from "./routes/index";
const { expressjwt: jwt } = require("express-jwt");
import { jwtSecret } from "./utils/jwt.js";

// 将jwt作为中间件使用
const jwtMiddleware = jwt({
  secret: jwtSecret, // 替换为你的密钥
  algorithms: ["HS256"], // 指定要使用的算法
  requestProperty: "auth", // 可选：将解析后的 token 存储在 req 的这个属性上（默认为 'user'）
}).unless({
  path: [
    // 在这里指定不需要 JWT 验证的路由路径
    "/usersSave",
    "/usersLogin",
    "/queryArticle",
    "/classificationArticle",
  ],
});

AppDataSource.initialize()
  .then(async () => {
    const app = express();
    // 设置post请求头
    app.use(bodyParser.json());
    app.use(jwtMiddleware);
    Routes.forEach((route) => {
      (app as any)[route.method](
        route.route,
        (req: Request, res: Response, next: Function) => {
          const result = new (route.controller as any)()[route.action](
            req,
            res,
            next
          );
          if (result instanceof Promise) {
            result.then((result) =>
              result !== null && result !== undefined
                ? res.send(result)
                : undefined
            );
          } else if (result !== null && result !== undefined) {
            res.json(result);
          }
        }
      );
    });
    app.listen(9000);
  })
  .catch((error) => console.log(error));
